package io.vector.study.algorithm.linkedlist;

import java.util.Objects;

/**
 * Created by vector on 2017/3/17.
 */
public class LinkedListBuilder<E> {

    private LinkedNode<E> root;

    public LinkedListBuilder appendItem(E item) {
        LinkedNode<E> node = new LinkedNodeImpl<>(item);
        return appendNode(node);
    }

    public LinkedListBuilder appendNode(LinkedNode<E> node) {
        Objects.requireNonNull(node);

        if (this.root == null) {
            this.root = node;
        } else {
            appendNodeToTail(node);
        }
        return this;
    }

    private void appendNodeToTail(LinkedNode<E> node) {
        LinkedNode<E> iterator = root;
        while (iterator.hasNext()) {
            iterator = iterator.next();
        }
        iterator.next(node);
    }

    public LinkedNode<E> build() {
        return this.root;
    }

}
